package stdio.costa.imoca.api;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import stdio.costa.imoca.model.Image;
import stdio.costa.imoca.spi.ImageServiceFactory;
import stdio.costa.imoca.spi.ImageServiceSpi;
import stdio.costa.imoca.utils.IOUtils;

import com.sun.jersey.multipart.BodyPartEntity;
import com.sun.jersey.multipart.FormDataBodyPart;
import com.sun.jersey.multipart.FormDataParam;

@Path("/image")
@Component
@Scope("request")
public class ImageApi {

	private static final Logger logger = LoggerFactory.getLogger(ImageApi.class);

	@Autowired
	private ImageServiceFactory imageServiceFactory;

	@PersistenceContext
	private EntityManager entityManager;

	@POST
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	@Produces({ "application/json;qs=1", "application/xml;qs=.5" })
	@Transactional
	public Image create(@FormDataParam("image") FormDataBodyPart bodyPart) throws IOException {
		BodyPartEntity entity = (BodyPartEntity) bodyPart.getEntity();
		InputStream in = entity.getInputStream();
		Image image = saveLocally(in, bodyPart.getMediaType().toString());
		
		if (image != null) {
			logger.info("Image is created {}", image.getUuid());
			getImageService().create(image);
		}
		return image;
	}

	@Path("/{uuid}")
	@GET
	@Produces({ "image/jpeg", "image/png", "image/bmp" })
	public Response get(@PathParam("uuid") String uuid, @QueryParam("width") Integer width, @QueryParam("height") Integer height)
			throws IOException {
		Image image = entityManager.find(Image.class, uuid);
		return Response.ok(new ByteArrayInputStream(image.getData())).build();
	}
	
	protected ImageServiceSpi getImageService() {
		return imageServiceFactory.getImageService();
	}
	
	protected Image saveLocally(InputStream in, String mediaType) throws IOException {
		byte[] data = IOUtils.read(in);
		if (data.length == 0)
			return null;
		// FIXME add owner
		Image image = new Image(data, mediaType, null);
		entityManager.persist(image);
		return image;
	}
	
	@Path("/imgsrc")
	@GET
	public Response imgsrc() throws URISyntaxException {
		String img = "http://i0.sinaimg.cn/ty/1098/2012/0531/U2035P6T1098D1F32491DT20130218170135.jpg";
		System.out.println("http://i0.sinaimg.cn/ty/1098/2012/0531/U2035P6T1098D1F32491DT20130218170135.jpg");
		return Response.seeOther(new URI(img)).build();
	}
}
